/**
 * 
 */
package com.srini.util;

import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.apache.derby.jdbc.EmbeddedConnectionPoolDataSource;

/**
 * @author Sriniz
 *
 */
public class ConnectionUtil {

	private Connection con = null;

	private static String driver = "org.apache.derby.jdbc.EmbeddedDriver";
	private static String dbPath = System.getProperty("user.home");
	private static String dbName = dbPath + File.separator + ".trms";

	private static String connectionURL = null;

	public Connection getConnection() {
		try {
			if (con == null) {
				System.out.print("Connecting to database... ");
				Class.forName(driver);
				connectionURL = getConnectionURL();
				con = DriverManager.getConnection(connectionURL);
//				con.setAutoCommit(false);
				System.out.println(" SUCCESS");
			}
		} catch (SQLException e) {
			System.out.println(e.getMessage());
		} catch (ClassNotFoundException e) {
			System.out.println("Drivers not found.");
			e.printStackTrace();
		}
		
		return con;
	}
	
	private static String getConnectionURL() {

//		String url = "jdbc:derby:" + dbName + ";create=true;user="
//				+ Encryptor.decode("744172576d65736c") + ";password="
//				+ Encryptor.decode("744172576d65736c");
		
		String url = "jdbc:derby:" + dbName + ";create=true;user=trms;password=trms;";

		return url;
	}
	public static void main(String[] args) {
//		getConnection();
		try {
		EmbeddedConnectionPoolDataSource dataSource = new org.apache.derby.jdbc.EmbeddedConnectionPoolDataSource();
		dataSource.setDatabaseName (dbName);
		dataSource.setCreateDatabase ("create");
		ConnectionPoolManager poolMgr = new ConnectionPoolManager(dataSource, 30);
		Connection connection = poolMgr.getConnection();
		System.out.println(connection);
		connection.close();
		}catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void closeConnection() {

		if (con != null) {
			try {
				con.close();
				con = null;
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}
